package com.ruoyi.huanjing.controller;

import com.ruoyi.common.annotation.Anonymous;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import ucar.ma2.Array;
import ucar.ma2.Index;
import ucar.ma2.InvalidRangeException;
import ucar.nc2.NetcdfFile;
import ucar.nc2.Variable;

import java.io.IOException;
import java.util.Arrays;

@RestController
public class Read2D {

    @Anonymous
    @GetMapping("/read2D")
    public short[][] read2D(String filePath, String variableName) throws IOException {
        //  filePath = "E:\\localfile\\MYD021KM.A2017314.0345.061.2017314164621.hdf";
        //  variableName = "DC_Restore_Change_for_Reflective_1km_Bands";
        try (NetcdfFile ncFile = NetcdfFile.open(filePath)) {
            // 获取变量
            Variable thermalDetectorVar = ncFile.findVariable(variableName);

            if (thermalDetectorVar == null) {
                System.err.println("变量未找到");
                return null;
            }

            // 读取数据
            Array thermalData = thermalDetectorVar.read();

            // 获取数组维度
            int[] shape = thermalData.getShape();

            // 如果维度大于 2，选择最后两个维度的切片
            if (shape.length > 2) {
                int[] sectionOrigin = new int[shape.length];
                int[] sectionShape = new int[shape.length];
                // 将 sectionOrigin 所有维度初始化为 0
                Arrays.fill(sectionOrigin, 0);
                // 将非最后两个维度的 sectionShape 初始化为 1
                Arrays.fill(sectionShape, 1);
                sectionShape[shape.length - 2] = shape[shape.length - 2];
                sectionShape[shape.length - 1] = shape[shape.length - 1];

                try {
                    thermalData = thermalData.section(sectionOrigin, sectionShape);
                } catch (InvalidRangeException e) {
                    // 可根据实际需求修改异常处理逻辑
                    e.printStackTrace();
                    return null;
                }
                shape = new int[]{shape[shape.length - 2], shape[shape.length - 1]};
            }

            int dim1 = shape[0];
            int dim2 = shape[1];

            // 创建Index对象用于访问数组元素
            Index index = thermalData.getIndex();

            // 转换为二维数组
            short[][] detectorData = new short[dim1][dim2];
            for (int i = 0; i < dim1; i++) {
                for (int j = 0; j < dim2; j++) {
                    detectorData[i][j] = thermalData.getShort(index.set(i, j));
                }
            }
            return detectorData;
        } catch (IOException e) {
            System.err.println("处理文件时出错: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
}
